<script setup lang="ts">
import SubMenuTitle from './SubMenuTitle.vue'
import { useMenuStore, useTabStore } from '@/stores'
import type { MenuItem } from '@/types/store'
import { useRouter } from 'vue-router'

export interface Props {
  menus: MenuItem[]
}

withDefaults(defineProps<Props>(), {
  menus: () => []
})

const menuStore = useMenuStore()
const tabStore = useTabStore()
const router = useRouter()

const onClick = (menu: MenuItem) => {
  const { name, full, title, icon } = menu
  // 全局路由不去记录 menuActive，这样跳回来刷新就可以是上次访问 menuActive 的了
  if (full) {
    router.push({ name })
    return
  }
  tabStore.push({
    title,
    icon,
    name,
    source: 'menu'
  })
  menuStore.menuActive = name
  tabStore.tabActive = name
  router.push({ name })
}
</script>

<template>
  <template v-for="menu in menus" :key="menu.name">
    <el-sub-menu v-if="menu.children.length" :index="menu.name">
      <template #title>
        <SubMenuTitle :icon="menu.icon" :title="menu.title" />
      </template>
      <SubMenu :menus="menu.children" />
    </el-sub-menu>
    <el-menu-item v-else :index="menu.name" @click="onClick(menu)">
      <SubMenuTitle :icon="menu.icon" :title="menu.title" />
    </el-menu-item>
  </template>
</template>

<style scoped lang="scss"></style>
